-- Migration 1000: Supplier Invoice Enhancements
-- Adds support for accounting integration (modkonti) and line item tracking
-- Date: 2026-01-06

-- Add columns to supplier_invoice_lines for accounting integration
ALTER TABLE supplier_invoice_lines 
ADD COLUMN IF NOT EXISTS contra_account VARCHAR(10),
ADD COLUMN IF NOT EXISTS line_purpose VARCHAR(50),
ADD COLUMN IF NOT EXISTS resale_customer_id INT REFERENCES customers(id),
ADD COLUMN IF NOT EXISTS resale_order_number VARCHAR(50),
ADD COLUMN IF NOT EXISTS is_invoiced_to_customer BOOLEAN DEFAULT FALSE,
ADD COLUMN IF NOT EXISTS invoiced_date TIMESTAMP;

-- Create index for faster filtering by purpose
CREATE INDEX IF NOT EXISTS idx_supplier_invoice_lines_purpose 
ON supplier_invoice_lines(line_purpose);

-- Create index for faster filtering by resale status
CREATE INDEX IF NOT EXISTS idx_supplier_invoice_lines_resale 
ON supplier_invoice_lines(is_invoiced_to_customer);

-- Create table to cache e-conomic chart of accounts (kontoplan)
CREATE TABLE IF NOT EXISTS economic_accounts (
    account_number INT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    account_type VARCHAR(50),
    vat_code VARCHAR(10),
    balance DECIMAL(15, 2),
    is_active BOOLEAN DEFAULT TRUE,
    last_synced TIMESTAMP DEFAULT NOW(),
    created_at TIMESTAMP DEFAULT NOW()
);

-- Create index for fast account lookups
CREATE INDEX IF NOT EXISTS idx_economic_accounts_active 
ON economic_accounts(is_active) WHERE is_active = TRUE;

-- Create index for account type filtering
CREATE INDEX IF NOT EXISTS idx_economic_accounts_type 
ON economic_accounts(account_type);

-- Add comments for documentation
COMMENT ON COLUMN supplier_invoice_lines.contra_account IS 'e-conomic account number (modkonto) for this line item';
COMMENT ON COLUMN supplier_invoice_lines.line_purpose IS 'Purpose: resale, internal, project, stock';
COMMENT ON COLUMN supplier_invoice_lines.resale_customer_id IS 'Customer ID if this line is for resale';
COMMENT ON COLUMN supplier_invoice_lines.resale_order_number IS 'Order number if linked to customer order';
COMMENT ON COLUMN supplier_invoice_lines.is_invoiced_to_customer IS 'TRUE when this line has been invoiced to customer';
COMMENT ON COLUMN supplier_invoice_lines.invoiced_date IS 'Date when line was invoiced to customer';

COMMENT ON TABLE economic_accounts IS 'Cached e-conomic chart of accounts (kontoplan) for dropdown menus';
COMMENT ON COLUMN economic_accounts.account_number IS 'e-conomic account number (e.g., 5810, 1970)';
COMMENT ON COLUMN economic_accounts.name IS 'Account name/description';
COMMENT ON COLUMN economic_accounts.account_type IS 'Type: profitAndLoss, status, etc.';
COMMENT ON COLUMN economic_accounts.vat_code IS 'Associated VAT code if applicable';
COMMENT ON COLUMN economic_accounts.last_synced IS 'Last time this account was updated from e-conomic API';

-- Success message
DO $$
BEGIN
    RAISE NOTICE '✅ Migration 1000 completed: Supplier invoice enhancements added';
END $$;
