-- Migration 175: Supplier invoice attachments
-- Created: 2026-04-13

CREATE TABLE IF NOT EXISTS supplier_invoice_attachments (
    id BIGSERIAL PRIMARY KEY,
    supplier_invoice_id INTEGER NOT NULL REFERENCES supplier_invoices(id) ON DELETE CASCADE,
    source_type VARCHAR(30) NOT NULL DEFAULT 'upload',
    source_email_id INTEGER REFERENCES email_messages(id) ON DELETE SET NULL,
    source_email_attachment_id INTEGER REFERENCES email_attachments(id) ON DELETE SET NULL,
    filename VARCHAR(255) NOT NULL,
    mime_type VARCHAR(120),
    file_path TEXT,
    size_bytes BIGINT,
    notes TEXT,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'chk_supplier_invoice_attachments_source_type'
    ) THEN
        ALTER TABLE supplier_invoice_attachments
        ADD CONSTRAINT chk_supplier_invoice_attachments_source_type
        CHECK (source_type IN ('email', 'upload', 'manual'));
    END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_supplier_invoice_attachments_supplier_invoice_id
ON supplier_invoice_attachments(supplier_invoice_id);

CREATE INDEX IF NOT EXISTS idx_supplier_invoice_attachments_source_email_id
ON supplier_invoice_attachments(source_email_id)
WHERE source_email_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_supplier_invoice_attachments_source_email_attachment_id
ON supplier_invoice_attachments(source_email_attachment_id)
WHERE source_email_attachment_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_supplier_invoice_attachments_source_type
ON supplier_invoice_attachments(source_type);

COMMENT ON TABLE supplier_invoice_attachments IS 'Attachments linked to supplier invoices';
COMMENT ON COLUMN supplier_invoice_attachments.source_type IS 'Attachment source: email, upload, or manual';
COMMENT ON COLUMN supplier_invoice_attachments.source_email_id IS 'Source email id when attachment came from email';
COMMENT ON COLUMN supplier_invoice_attachments.source_email_attachment_id IS 'Source email attachment id when available';
