CREATE TABLE IF NOT EXISTS role (
    id BIGSERIAL PRIMARY KEY,
    name VARCHAR(50) UNIQUE NOT NULL
);

CREATE TABLE IF NOT EXISTS app_user (
    id BIGSERIAL PRIMARY KEY,
    username VARCHAR(100) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    enabled BOOLEAN NOT NULL DEFAULT TRUE
);

CREATE TABLE IF NOT EXISTS user_role (
    user_id BIGINT NOT NULL,
    role_id BIGINT NOT NULL,
    PRIMARY KEY (user_id, role_id),
    CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES app_user(id) ON DELETE CASCADE,
    CONSTRAINT fk_role FOREIGN KEY (role_id) REFERENCES role(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS adherent (
    id BIGSERIAL PRIMARY KEY,
    nom VARCHAR(100) NOT NULL,
    prenom VARCHAR(100) NOT NULL,
    date_naissance DATE NOT NULL,
    telephone VARCHAR(20),
    email VARCHAR(100),
    adresse TEXT,
    representant_legal VARCHAR(150)
);

CREATE TABLE IF NOT EXISTS categorie (
    id BIGSERIAL PRIMARY KEY,
    nom VARCHAR(20) UNIQUE NOT NULL,
    annee_min INT,
    annee_max INT,
    tarif_base DECIMAL(10,2) NOT NULL
);

CREATE TABLE IF NOT EXISTS licence (
    id BIGSERIAL PRIMARY KEY,
    adherent_id BIGINT NOT NULL,
    categorie_id BIGINT NOT NULL,
    saison VARCHAR(20) NOT NULL,
    etat VARCHAR(50) NOT NULL,
    CONSTRAINT fk_licence_adherent FOREIGN KEY (adherent_id) REFERENCES adherent(id) ON DELETE CASCADE,
    CONSTRAINT fk_licence_categorie FOREIGN KEY (categorie_id) REFERENCES categorie(id)
);

CREATE TABLE IF NOT EXISTS paiement (
    id BIGSERIAL PRIMARY KEY,
    licence_id BIGINT NOT NULL,
    montant DECIMAL(10,2) NOT NULL,
    date_paiement DATE NOT NULL,
    mode_paiement VARCHAR(50) NOT NULL,
    CONSTRAINT fk_paiement_licence FOREIGN KEY (licence_id) REFERENCES licence(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS equipement (
    id BIGSERIAL PRIMARY KEY,
    nom VARCHAR(100) NOT NULL,
    description TEXT,
    obligatoire BOOLEAN NOT NULL DEFAULT FALSE
);

CREATE TABLE IF NOT EXISTS dotation (
    id BIGSERIAL PRIMARY KEY,
    licence_id BIGINT NOT NULL,
    equipement_id BIGINT NOT NULL,
    taille VARCHAR(10),
    flocage VARCHAR(50),
    fourni BOOLEAN NOT NULL DEFAULT FALSE,
    CONSTRAINT fk_dotation_licence FOREIGN KEY (licence_id) REFERENCES licence(id) ON DELETE CASCADE,
    CONSTRAINT fk_dotation_equipement FOREIGN KEY (equipement_id) REFERENCES equipement(id)
);
