CREATE TABLE IF NOT EXISTS project_chickin_details (
    id BIGSERIAL PRIMARY KEY,
    project_chickin_id BIGINT NOT NULL,
    product_warehouse_id BIGINT NOT NULL,
    quantity NUMERIC(15, 3) NOT NULL,
    created_by BIGINT NOT NULL,
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now(),
    deleted_at TIMESTAMPTZ
);


DO $$
BEGIN
    IF to_regclass('project_chickins') IS NOT NULL THEN
        ALTER TABLE project_chickin_details
            ADD CONSTRAINT fk_project_chickin_id
            FOREIGN KEY (project_chickin_id)
            REFERENCES project_chickins(id)
            ON DELETE CASCADE ON UPDATE CASCADE;
    END IF;

    IF to_regclass('product_warehouses') IS NOT NULL THEN
        ALTER TABLE project_chickin_details
            ADD CONSTRAINT fk_product_warehouse_id
            FOREIGN KEY (product_warehouse_id)
            REFERENCES product_warehouses(id)
            ON DELETE RESTRICT ON UPDATE CASCADE;
    END IF;

    IF to_regclass('users') IS NOT NULL THEN
        ALTER TABLE project_chickin_details
            ADD CONSTRAINT fk_created_by
            FOREIGN KEY (created_by)
            REFERENCES users(id)
            ON DELETE RESTRICT ON UPDATE CASCADE;
    END IF;
END $$;

-- INDEXES
CREATE INDEX IF NOT EXISTS idx_project_chickin_details_project_chickin_id ON project_chickin_details (project_chickin_id);

CREATE INDEX IF NOT EXISTS idx_project_chickin_details_product_warehouse_id ON project_chickin_details (product_warehouse_id);

CREATE INDEX IF NOT EXISTS idx_project_chickin_details_created_by ON project_chickin_details (created_by);
