CREATE TABLE IF NOT EXISTS seed_sources (
    id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    public_id varchar(64) NOT NULL,
    batch_id uuid,
    parent_id uuid,
    supplier varchar(128) NOT NULL,
    seed_batch_no varchar(64) NOT NULL,
    quarantine_no varchar(64),
    variety varchar(64),
    certificate_url varchar(512),
    entry_at timestamptz,
    note text,
    created_by uuid,
    created_at timestamptz NOT NULL DEFAULT now(),
    updated_at timestamptz NOT NULL DEFAULT now()
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_seed_sources_public_id ON seed_sources (public_id);
CREATE INDEX IF NOT EXISTS idx_seed_sources_batch_id ON seed_sources (batch_id);
CREATE INDEX IF NOT EXISTS idx_seed_sources_parent_id ON seed_sources (parent_id);

CREATE TABLE IF NOT EXISTS disinfection_records (
    id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    room_id uuid,
    batch_id uuid,
    kind varchar(16) NOT NULL DEFAULT 'plan',
    plan_id uuid,
    agent varchar(128) NOT NULL,
    concentration varchar(64) NOT NULL,
    amount varchar(64),
    planned_at timestamptz,
    executed_at timestamptz,
    executor_id uuid,
    reviewed_at timestamptz,
    reviewer_id uuid,
    photo_url varchar(512),
    note text,
    created_by uuid,
    created_at timestamptz NOT NULL DEFAULT now(),
    updated_at timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_disinfection_records_room_id ON disinfection_records (room_id);
CREATE INDEX IF NOT EXISTS idx_disinfection_records_batch_id ON disinfection_records (batch_id);
CREATE INDEX IF NOT EXISTS idx_disinfection_records_plan_id ON disinfection_records (plan_id);

CREATE TABLE IF NOT EXISTS identity_links (
    id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    public_id varchar(64) NOT NULL,
    entity_type varchar(16) NOT NULL,
    entity_id varchar(128) NOT NULL,
    version integer NOT NULL DEFAULT 1,
    created_at timestamptz NOT NULL DEFAULT now(),
    updated_at timestamptz NOT NULL DEFAULT now()
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_identity_links_public_id ON identity_links (public_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_identity_links_entity ON identity_links (entity_type, entity_id);
CREATE INDEX IF NOT EXISTS idx_identity_links_entity_type ON identity_links (entity_type);

ALTER TABLE batches
    ADD COLUMN IF NOT EXISTS seed_source_id uuid;

CREATE INDEX IF NOT EXISTS idx_batches_seed_source_id ON batches (seed_source_id);
