-- Migration: Auto-populate org_id and tenant_id on time_clocks insert
-- Date: 2026-03-21
-- Description: Trigger to set org_id and tenant_id from the clocking user's
--              org membership (or branch membership as fallback) so that
--              employees who lack user_org_memberships records are still
--              correctly scoped.

CREATE OR REPLACE FUNCTION fn_time_clocks_set_org()
RETURNS trigger AS $$
BEGIN
    IF NEW.org_id IS NULL THEN
        NEW.org_id := '0199b208-8943-7ca3-ba31-781efbe25058'::uuid;
    END IF;

    IF NEW.tenant_id IS NULL THEN
        NEW.tenant_id := '0199b208-8943-7ca3-ba31-781efbe25058'::uuid;
    END IF;

    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trg_time_clocks_set_org ON time_clocks;
CREATE TRIGGER trg_time_clocks_set_org
BEFORE INSERT ON time_clocks
FOR EACH ROW
EXECUTE FUNCTION fn_time_clocks_set_org();
