DO
$$
BEGIN
   IF NOT EXISTS (SELECT FROM pg_database WHERE datname = 'db.ProximaContracts') THEN
      CREATE DATABASE "db.ProximaContracts";
   END IF;
END
$$;

\c "db.ProximaContracts";

CREATE TABLE IF NOT EXISTS public.Rates (
    Id        INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    Name      VARCHAR(100) NOT NULL,
    Price     MONEY        NOT NULL
);

CREATE TABLE IF NOT EXISTS public.Contracts (
    Id                 INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    ContractorIdNumber VARCHAR(20)  NOT NULL,
    ContractorName     VARCHAR(50)  NOT NULL,
    ContractorSurname  VARCHAR(100) NOT NULL,
    ContractInitDate   TIMESTAMP    NOT NULL,
    RateId             INTEGER      NOT NULL,
    CONSTRAINT fk_contracts_rates
        FOREIGN KEY (RateId)
        REFERENCES public.Rates (Id)
        ON UPDATE CASCADE
        ON DELETE RESTRICT
);



CREATE INDEX IF NOT EXISTS idx_contracts_rateid
    ON public.Contracts (RateId);


INSERT INTO public.Rates 
    (Name, Price)
VALUES
    ('Basic',    0.10),
    ('Economy',  0.12),
    ('Standard', 0.15),
    ('Premium',  0.20),
    ('Ultra',    0.25);



INSERT INTO public.Contracts
        (ContractorIdNumber,
         ContractorName,
         ContractorSurname,
         ContractInitDate,
         RateId)
VALUES
    ('A12345678', 'John',   'Smith',     '2025-01-15 10:00:00', 1), 
    ('B23456789', 'Emily',  'Johnson',   '2025-02-20 11:30:00', 2), 
    ('C34567890', 'Carlos', 'García',    '2025-03-05 09:00:00', 3), 
    ('D45678901', 'Sofía',  'Martínez',  '2025-04-12 14:45:00', 4), 
    ('E56789012', 'Liam',   'Brown',     '2025-05-01 08:20:00', 5); 