-- Company profile + email (SMTP) settings + SETTINGS RBAC module

CREATE TABLE IF NOT EXISTS company (
  id         BIGINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
  org_name   VARCHAR(200),
  gstin      VARCHAR(15),
  mobile     VARCHAR(20),
  email      VARCHAR(200),
  website    VARCHAR(255),
  logo_path  VARCHAR(500),
  address    TEXT,
  city       VARCHAR(100),
  state      VARCHAR(100),
  pincode    VARCHAR(10),
  created_by BIGINT,
  updated_by BIGINT,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

ALTER TABLE company
  ADD COLUMN IF NOT EXISTS gstin VARCHAR(15);

CREATE TABLE IF NOT EXISTS email_settings (
  id            BIGINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
  smtp_host     VARCHAR(255),
  smtp_port     INTEGER NOT NULL DEFAULT 587,
  smtp_username VARCHAR(200),
  smtp_password VARCHAR(500),
  sender_email  VARCHAR(200),
  sender_name   VARCHAR(200),
  created_by    BIGINT,
  updated_by    BIGINT,
  created_at    TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at    TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

INSERT INTO company (id, org_name)
VALUES (1, '')
ON CONFLICT (id) DO NOTHING;

INSERT INTO email_settings (id, smtp_port)
VALUES (1, 587)
ON CONFLICT (id) DO NOTHING;

INSERT INTO modules (code, name, sort_order, is_active)
VALUES ('SETTINGS', 'Settings', 90, true)
ON CONFLICT (code) DO UPDATE SET name = EXCLUDED.name, sort_order = EXCLUDED.sort_order, is_active = true;

INSERT INTO permissions (module_id, action, is_active)
SELECT m.id, a.action, true
FROM modules m
CROSS JOIN (VALUES ('view'), ('edit')) AS a(action)
WHERE m.code = 'SETTINGS'
ON CONFLICT (module_id, action) DO UPDATE SET is_active = true;

INSERT INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
JOIN permissions p ON p.action IN ('view', 'edit')
JOIN modules m ON m.id = p.module_id AND m.code = 'SETTINGS'
WHERE r.name = 'Super Admin' AND r.deleted_at IS NULL
ON CONFLICT (role_id, permission_id) DO NOTHING;
