-- Migration v4 : actions sur les rows du planning importé
--   - is_eligible        : ligne marquée éligible au patching (passe au workflow iexec)
--   - reported_to_sheet  : si reportée, semaine cible (ex 'S23')
--   - report_reason      : raison du report
--   - last_action_*      : tracking dernière action (qui/quand)
-- + table patch_planning_row_log : audit log de chaque action posée
-- Idempotent

ALTER TABLE public.patch_planning_import_rows
    ADD COLUMN IF NOT EXISTS is_eligible       boolean NOT NULL DEFAULT false,
    ADD COLUMN IF NOT EXISTS reported_to_sheet text,
    ADD COLUMN IF NOT EXISTS report_reason     text,
    ADD COLUMN IF NOT EXISTS last_action_at    timestamptz,
    ADD COLUMN IF NOT EXISTS last_action_by    integer REFERENCES public.users(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS idx_pp_rows_eligible
    ON public.patch_planning_import_rows(import_id, sheet_name)
    WHERE is_eligible = true;

CREATE TABLE IF NOT EXISTS public.patch_planning_row_log (
    id SERIAL PRIMARY KEY,
    row_id integer NOT NULL REFERENCES public.patch_planning_import_rows(id) ON DELETE CASCADE,
    action text NOT NULL,                 -- 'eligible', 'unset_eligible', 'report', 'unset_report'
    details jsonb,                        -- {target_sheet, reason, ...}
    performed_by integer REFERENCES public.users(id) ON DELETE SET NULL,
    performed_at timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_pp_row_log_row ON public.patch_planning_row_log(row_id);
CREATE INDEX IF NOT EXISTS idx_pp_row_log_at ON public.patch_planning_row_log(performed_at DESC);

GRANT SELECT, INSERT, UPDATE, DELETE ON public.patch_planning_row_log TO patchcenter;
GRANT USAGE, SELECT ON SEQUENCE public.patch_planning_row_log_id_seq TO patchcenter;
