CREATE TABLE IF NOT EXISTS users (
    id            BIGSERIAL PRIMARY KEY,
    name          TEXT NOT NULL,
    email         TEXT NOT NULL UNIQUE,
    password_hash TEXT NOT NULL,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS roles (
    id           BIGSERIAL PRIMARY KEY,
    key          TEXT NOT NULL UNIQUE,
    name         TEXT NOT NULL,
    description  TEXT,
    is_system    BOOLEAN NOT NULL DEFAULT false,
    is_superadmin BOOLEAN NOT NULL DEFAULT false,
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS permissions (
    id     BIGSERIAL PRIMARY KEY,
    key    TEXT NOT NULL UNIQUE,
    module TEXT NOT NULL,
    label  TEXT NOT NULL,
    sort   INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE IF NOT EXISTS role_permissions (
    role_id       BIGINT NOT NULL REFERENCES roles (id) ON DELETE CASCADE,
    permission_id BIGINT NOT NULL REFERENCES permissions (id) ON DELETE CASCADE,
    PRIMARY KEY (role_id, permission_id)
);

CREATE TABLE IF NOT EXISTS settings (
    key        TEXT PRIMARY KEY,
    value      TEXT,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

ALTER TABLE users ADD COLUMN IF NOT EXISTS role_id BIGINT REFERENCES roles (id) ON DELETE SET NULL;
ALTER TABLE users ADD COLUMN IF NOT EXISTS is_active BOOLEAN NOT NULL DEFAULT true;
CREATE INDEX IF NOT EXISTS idx_users_role ON users (role_id);

CREATE TABLE IF NOT EXISTS companies (
    id         BIGSERIAL PRIMARY KEY,
    name       TEXT NOT NULL,
    industry   TEXT,
    website    TEXT,
    phone      TEXT,
    email      TEXT,
    city       TEXT,
    country    TEXT NOT NULL DEFAULT 'Indonesia',
    address    TEXT,
    notes      TEXT,
    owner_id   BIGINT REFERENCES users (id) ON DELETE SET NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS contacts (
    id         BIGSERIAL PRIMARY KEY,
    first_name TEXT NOT NULL,
    last_name  TEXT,
    email      TEXT,
    phone      TEXT,
    job_title  TEXT,
    company_id BIGINT REFERENCES companies (id) ON DELETE SET NULL,
    status     TEXT NOT NULL DEFAULT 'lead' CHECK (status IN ('lead', 'prospect', 'customer', 'inactive')),
    notes      TEXT,
    owner_id   BIGINT REFERENCES users (id) ON DELETE SET NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS deals (
    id                  BIGSERIAL PRIMARY KEY,
    title               TEXT NOT NULL,
    company_id          BIGINT REFERENCES companies (id) ON DELETE SET NULL,
    contact_id          BIGINT REFERENCES contacts (id) ON DELETE SET NULL,
    value               NUMERIC(15, 2) NOT NULL DEFAULT 0 CHECK (value >= 0),
    stage               TEXT NOT NULL DEFAULT 'lead' CHECK (stage IN ('lead', 'qualified', 'proposal', 'negotiation', 'won', 'lost')),
    expected_close_date DATE,
    owner_id            BIGINT REFERENCES users (id) ON DELETE SET NULL,
    notes               TEXT,
    closed_at           TIMESTAMPTZ,
    created_at          TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at          TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS activities (
    id         BIGSERIAL PRIMARY KEY,
    type       TEXT NOT NULL DEFAULT 'task' CHECK (type IN ('call', 'email', 'meeting', 'task')),
    subject    TEXT NOT NULL,
    notes      TEXT,
    due_at     TIMESTAMPTZ,
    is_done    BOOLEAN NOT NULL DEFAULT false,
    done_at    TIMESTAMPTZ,
    contact_id BIGINT REFERENCES contacts (id) ON DELETE SET NULL,
    company_id BIGINT REFERENCES companies (id) ON DELETE SET NULL,
    deal_id    BIGINT REFERENCES deals (id) ON DELETE SET NULL,
    owner_id   BIGINT REFERENCES users (id) ON DELETE SET NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS quotations (
    id                BIGSERIAL PRIMARY KEY,
    number            TEXT NOT NULL UNIQUE,
    deal_id           BIGINT REFERENCES deals (id) ON DELETE SET NULL,
    company_id        BIGINT REFERENCES companies (id) ON DELETE SET NULL,
    contact_id        BIGINT REFERENCES contacts (id) ON DELETE SET NULL,
    invoice_address   TEXT,
    delivery_address  TEXT,
    quotation_date    DATE NOT NULL DEFAULT CURRENT_DATE,
    valid_until       DATE,
    payment_terms     INTEGER NOT NULL DEFAULT 30 CHECK (payment_terms >= 0),
    reference         TEXT,
    notes             TEXT,
    terms             TEXT,
    status            TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'sent', 'order', 'canceled')),
    sent_at           TIMESTAMPTZ,
    confirmed_at      TIMESTAMPTZ,
    canceled_at       TIMESTAMPTZ,
    owner_id          BIGINT REFERENCES users (id) ON DELETE SET NULL,
    created_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at        TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS quotation_lines (
    id           BIGSERIAL PRIMARY KEY,
    quotation_id BIGINT NOT NULL REFERENCES quotations (id) ON DELETE CASCADE,
    sequence     INTEGER NOT NULL DEFAULT 0,
    line_type    TEXT NOT NULL DEFAULT 'product' CHECK (line_type IN ('product', 'section', 'note')),
    description  TEXT NOT NULL,
    quantity     NUMERIC(15, 2) NOT NULL DEFAULT 1 CHECK (quantity >= 0),
    unit_price   NUMERIC(15, 2) NOT NULL DEFAULT 0 CHECK (unit_price >= 0),
    tax_rate     NUMERIC(5, 2) NOT NULL DEFAULT 11 CHECK (tax_rate >= 0 AND tax_rate <= 100)
);

CREATE TABLE IF NOT EXISTS invoices (
    id              BIGSERIAL PRIMARY KEY,
    number          TEXT NOT NULL UNIQUE,
    quotation_id    BIGINT REFERENCES quotations (id) ON DELETE SET NULL,
    deal_id         BIGINT REFERENCES deals (id) ON DELETE SET NULL,
    company_id      BIGINT REFERENCES companies (id) ON DELETE SET NULL,
    contact_id      BIGINT REFERENCES contacts (id) ON DELETE SET NULL,
    billing_address TEXT,
    invoice_date    DATE NOT NULL DEFAULT CURRENT_DATE,
    due_date        DATE,
    payment_terms   INTEGER NOT NULL DEFAULT 30 CHECK (payment_terms >= 0),
    reference       TEXT,
    notes           TEXT,
    status          TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'posted', 'paid', 'canceled')),
    posted_at       TIMESTAMPTZ,
    paid_at         TIMESTAMPTZ,
    canceled_at     TIMESTAMPTZ,
    payment_method  TEXT,
    owner_id        BIGINT REFERENCES users (id) ON DELETE SET NULL,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS invoice_lines (
    id          BIGSERIAL PRIMARY KEY,
    invoice_id  BIGINT NOT NULL REFERENCES invoices (id) ON DELETE CASCADE,
    sequence    INTEGER NOT NULL DEFAULT 0,
    line_type   TEXT NOT NULL DEFAULT 'product' CHECK (line_type IN ('product', 'section', 'note')),
    description TEXT NOT NULL,
    quantity    NUMERIC(15, 2) NOT NULL DEFAULT 1 CHECK (quantity >= 0),
    unit_price  NUMERIC(15, 2) NOT NULL DEFAULT 0 CHECK (unit_price >= 0),
    tax_rate    NUMERIC(5, 2) NOT NULL DEFAULT 11 CHECK (tax_rate >= 0 AND tax_rate <= 100)
);

CREATE TABLE IF NOT EXISTS invoice_payments (
    id           BIGSERIAL PRIMARY KEY,
    invoice_id   BIGINT NOT NULL REFERENCES invoices (id) ON DELETE CASCADE,
    amount       NUMERIC(15, 2) NOT NULL CHECK (amount > 0),
    payment_date DATE NOT NULL DEFAULT CURRENT_DATE,
    method       TEXT NOT NULL DEFAULT 'Transfer Bank',
    memo         TEXT,
    created_by   BIGINT REFERENCES users (id) ON DELETE SET NULL,
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

ALTER TABLE invoices ADD COLUMN IF NOT EXISTS invoice_type TEXT NOT NULL DEFAULT 'regular';
ALTER TABLE invoices ADD COLUMN IF NOT EXISTS down_payment_percent NUMERIC(5, 2);
ALTER TABLE invoices ADD COLUMN IF NOT EXISTS origin_invoice_id BIGINT REFERENCES invoices (id) ON DELETE SET NULL;
ALTER TABLE invoices ADD COLUMN IF NOT EXISTS last_emailed_at TIMESTAMPTZ;
ALTER TABLE invoices ADD COLUMN IF NOT EXISTS last_emailed_to TEXT;
ALTER TABLE invoices ADD COLUMN IF NOT EXISTS last_reminded_at TIMESTAMPTZ;
ALTER TABLE invoices ADD COLUMN IF NOT EXISTS last_reminded_channel TEXT;
ALTER TABLE invoices ADD COLUMN IF NOT EXISTS last_reminded_to TEXT;
ALTER TABLE invoices ADD COLUMN IF NOT EXISTS reminder_count INTEGER NOT NULL DEFAULT 0;
ALTER TABLE invoices DROP CONSTRAINT IF EXISTS invoices_invoice_type_check;
ALTER TABLE invoices ADD CONSTRAINT invoices_invoice_type_check CHECK (invoice_type IN ('regular', 'down_payment', 'credit_note'));

ALTER TABLE invoice_lines ADD COLUMN IF NOT EXISTS source_invoice_id BIGINT REFERENCES invoices (id) ON DELETE SET NULL;
ALTER TABLE invoice_lines DROP CONSTRAINT IF EXISTS invoice_lines_line_type_check;
ALTER TABLE invoice_lines ADD CONSTRAINT invoice_lines_line_type_check
    CHECK (line_type IN ('product', 'section', 'note', 'down_payment'));
ALTER TABLE invoice_lines DROP CONSTRAINT IF EXISTS invoice_lines_unit_price_check;
ALTER TABLE invoice_lines ADD CONSTRAINT invoice_lines_unit_price_check
    CHECK (unit_price >= 0 OR line_type = 'down_payment');

CREATE INDEX IF NOT EXISTS idx_invoices_type ON invoices (invoice_type);
CREATE INDEX IF NOT EXISTS idx_invoices_origin ON invoices (origin_invoice_id);
CREATE INDEX IF NOT EXISTS idx_invoices_due ON invoices (due_date);
CREATE INDEX IF NOT EXISTS idx_invoice_lines_source ON invoice_lines (source_invoice_id);
CREATE INDEX IF NOT EXISTS idx_invoice_payments_invoice ON invoice_payments (invoice_id);

CREATE TABLE IF NOT EXISTS products (
    id          BIGSERIAL PRIMARY KEY,
    name        TEXT NOT NULL,
    sku         TEXT,
    description TEXT,
    unit_price  NUMERIC(15, 2) NOT NULL DEFAULT 0 CHECK (unit_price >= 0),
    tax_rate    NUMERIC(5, 2) NOT NULL DEFAULT 11 CHECK (tax_rate >= 0 AND tax_rate <= 100),
    is_active   BOOLEAN NOT NULL DEFAULT true,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_products_name ON products (lower(name));
CREATE INDEX IF NOT EXISTS idx_products_active ON products (is_active);

-- Backfill: faktur lunas lama (sebelum ada tabel pembayaran) dianggap satu pelunasan penuh.
INSERT INTO invoice_payments (invoice_id, amount, payment_date, method, memo, created_at)
SELECT i.id,
       totals.total,
       COALESCE(i.paid_at::date, i.invoice_date),
       COALESCE(i.payment_method, 'Transfer Bank'),
       'Pembayaran awal (migrasi)',
       COALESCE(i.paid_at, now())
FROM invoices i
JOIN LATERAL (
    SELECT COALESCE(sum(l.quantity * l.unit_price * (1 + l.tax_rate / 100.0)), 0) AS total
    FROM invoice_lines l
    WHERE l.invoice_id = i.id AND l.line_type IN ('product', 'down_payment')
) totals ON true
WHERE i.status = 'paid' AND totals.total > 0
  AND NOT EXISTS (SELECT 1 FROM invoice_payments p WHERE p.invoice_id = i.id);
CREATE INDEX IF NOT EXISTS idx_companies_name ON companies (lower(name));
CREATE INDEX IF NOT EXISTS idx_contacts_name ON contacts (lower(first_name || ' ' || COALESCE(last_name, '')));
CREATE INDEX IF NOT EXISTS idx_contacts_company ON contacts (company_id);
CREATE INDEX IF NOT EXISTS idx_contacts_status ON contacts (status);
CREATE INDEX IF NOT EXISTS idx_deals_stage ON deals (stage);
CREATE INDEX IF NOT EXISTS idx_deals_company ON deals (company_id);
CREATE INDEX IF NOT EXISTS idx_deals_contact ON deals (contact_id);
CREATE INDEX IF NOT EXISTS idx_activities_due ON activities (due_at);
CREATE INDEX IF NOT EXISTS idx_activities_done ON activities (is_done);
CREATE INDEX IF NOT EXISTS idx_quotations_status ON quotations (status);
CREATE INDEX IF NOT EXISTS idx_quotations_deal ON quotations (deal_id);
CREATE INDEX IF NOT EXISTS idx_quotations_company ON quotations (company_id);
CREATE INDEX IF NOT EXISTS idx_quotations_contact ON quotations (contact_id);
CREATE INDEX IF NOT EXISTS idx_quotation_lines_parent ON quotation_lines (quotation_id);
CREATE INDEX IF NOT EXISTS idx_invoices_status ON invoices (status);
CREATE INDEX IF NOT EXISTS idx_invoices_quotation ON invoices (quotation_id);
CREATE INDEX IF NOT EXISTS idx_invoices_deal ON invoices (deal_id);
CREATE INDEX IF NOT EXISTS idx_invoices_company ON invoices (company_id);
CREATE INDEX IF NOT EXISTS idx_invoice_lines_parent ON invoice_lines (invoice_id);

CREATE TABLE IF NOT EXISTS sales_targets (
    id            BIGSERIAL PRIMARY KEY,
    user_id       BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    period        DATE NOT NULL,
    target_amount NUMERIC(15, 2) NOT NULL DEFAULT 0 CHECK (target_amount >= 0),
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (user_id, period)
);

CREATE INDEX IF NOT EXISTS idx_sales_targets_period ON sales_targets (period);

CREATE TABLE IF NOT EXISTS record_logs (
    id          BIGSERIAL PRIMARY KEY,
    entity_type TEXT NOT NULL,
    entity_id   BIGINT NOT NULL,
    user_id     BIGINT REFERENCES users(id) ON DELETE SET NULL,
    kind        TEXT NOT NULL DEFAULT 'note',
    body        TEXT NOT NULL,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_record_logs_entity ON record_logs (entity_type, entity_id, created_at DESC);
