-- Migration: Add vendors table
-- Similar to customers but for suppliers/vendors

CREATE TABLE IF NOT EXISTS vendors (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    cvr_number VARCHAR(20) UNIQUE,
    
    -- Contact information
    email VARCHAR(255),
    phone VARCHAR(50),
    website VARCHAR(255),
    
    -- Address
    address TEXT,
    postal_code VARCHAR(10),
    city VARCHAR(100),
    country VARCHAR(100) DEFAULT 'Danmark',
    
    -- Integration IDs
    economic_supplier_number INTEGER UNIQUE,
    
    -- Vendor specific
    domain VARCHAR(255),
    email_pattern TEXT,
    category VARCHAR(50) DEFAULT 'general',
    priority INTEGER DEFAULT 50,
    
    -- Metadata
    notes TEXT,
    is_active BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    created_by_user_id INTEGER,
    updated_by_user_id INTEGER
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_vendors_name ON vendors(name);
CREATE INDEX IF NOT EXISTS idx_vendors_cvr ON vendors(cvr_number);
CREATE INDEX IF NOT EXISTS idx_vendors_domain ON vendors(domain);
CREATE INDEX IF NOT EXISTS idx_vendors_active ON vendors(is_active);

-- Updated timestamp trigger
CREATE OR REPLACE FUNCTION update_vendors_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER vendors_updated_at_trigger
    BEFORE UPDATE ON vendors
    FOR EACH ROW
    EXECUTE FUNCTION update_vendors_updated_at();

COMMENT ON TABLE vendors IS 'Suppliers and vendors';
COMMENT ON COLUMN vendors.category IS 'Vendor category: hardware, software, telecom, services, etc.';
COMMENT ON COLUMN vendors.priority IS 'Priority level 1-100, higher = more important';
