-- ============================================================================
-- Fixes: password_change_required + audit trigger UUID cast
-- ============================================================================

-- 1. All users use the passwords already set in the seed — no forced change
UPDATE users SET password_change_required = FALSE WHERE password_change_required = TRUE;

-- 2. Fix audit_password_change trigger: current_setting returns TEXT but
--    audit_logs.changed_by is UUID — cast to UUID to prevent type error
CREATE OR REPLACE FUNCTION audit_password_change()
RETURNS TRIGGER AS $$
BEGIN
    IF OLD.password_hash IS DISTINCT FROM NEW.password_hash THEN
        INSERT INTO audit_logs (
            table_name, record_id, action, old_data, new_data, changed_by, ip_address
        ) VALUES (
            'users',
            NEW.id,
            'UPDATE',
            jsonb_build_object('password_changed', true, 'password_change_required', OLD.password_change_required),
            jsonb_build_object('password_changed', true, 'password_change_required', NEW.password_change_required),
            NULLIF(current_setting('app.current_user_id', true), '')::UUID,
            NULLIF(current_setting('app.current_ip', true), '')
        );
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- 3. Re-enable the trigger (was disabled as workaround for the UUID bug)
ALTER TABLE users ENABLE TRIGGER trg_audit_password_change;
