-- Add modules table and update permissions structure

-- Create modules table
CREATE TABLE IF NOT EXISTS modules (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name TEXT NOT NULL,
    code TEXT UNIQUE NOT NULL,
    created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

CREATE TRIGGER trg_modules_updated_at
    BEFORE UPDATE ON modules
    FOR EACH ROW EXECUTE FUNCTION set_updated_at();

-- Add module_id and action columns to permissions table
ALTER TABLE permissions 
    ADD COLUMN IF NOT EXISTS module_id UUID REFERENCES modules(id) ON DELETE CASCADE,
    ADD COLUMN IF NOT EXISTS action TEXT;

-- Create index on module_id for better query performance
CREATE INDEX IF NOT EXISTS idx_permissions_module_id ON permissions(module_id);

-- Seed initial modules
INSERT INTO modules (name, code) VALUES 
    ('User Management', 'USER_MANAGEMENT'),
    ('Content Management', 'CONTENT_MANAGEMENT'),
    ('Letter Management', 'LETTER_MANAGEMENT'),
    ('Disposition Management', 'DISPOSITION_MANAGEMENT'),
    ('Reporting', 'REPORTING'),
    ('Settings', 'SETTINGS')
ON CONFLICT (code) DO NOTHING;

-- Update existing permissions to include module_id and action
-- This is a sample mapping - adjust based on your existing permission codes
UPDATE permissions SET 
    module_id = (SELECT id FROM modules WHERE code = 'LETTER_MANAGEMENT'),
    action = 'READ'
WHERE code LIKE 'letter.%' AND code LIKE '%.view';

UPDATE permissions SET 
    module_id = (SELECT id FROM modules WHERE code = 'LETTER_MANAGEMENT'),
    action = 'WRITE'
WHERE code LIKE 'letter.%' AND code LIKE '%.edit';

UPDATE permissions SET 
    module_id = (SELECT id FROM modules WHERE code = 'LETTER_MANAGEMENT'),
    action = 'CREATE'
WHERE code LIKE 'letter.%' AND code LIKE '%.create';

UPDATE permissions SET 
    module_id = (SELECT id FROM modules WHERE code = 'LETTER_MANAGEMENT'),
    action = 'DELETE'
WHERE code LIKE 'letter.%' AND code LIKE '%.delete';

-- Insert new structured permissions for each module
INSERT INTO permissions (module_id, action, code, description)
SELECT 
    m.id,
    a.action,
    CONCAT(m.code, '_', a.action),
    CONCAT('Can ', LOWER(a.action), ' ', LOWER(m.name))
FROM modules m
CROSS JOIN (VALUES ('READ'), ('WRITE'), ('CREATE'), ('DELETE')) AS a(action)
ON CONFLICT (code) DO NOTHING;