-- Migration 067: Add company_websites table for multiple website URLs per company
-- Date: 2026-02-17

CREATE TABLE IF NOT EXISTS company_websites (
    id SERIAL PRIMARY KEY,
    company_id INTEGER NOT NULL REFERENCES companies(id) ON DELETE CASCADE,
    url VARCHAR(500) NOT NULL,
    label VARCHAR(100),
    is_primary BOOLEAN DEFAULT FALSE,
    source VARCHAR(100),
    is_valid BOOLEAN DEFAULT TRUE,
    last_checked_at TIMESTAMP,
    check_status VARCHAR(50),
    created_at TIMESTAMP DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_company_websites_company_id ON company_websites(company_id);

-- Grant permissions
GRANT ALL ON TABLE company_websites TO nordabiz_app;
GRANT USAGE, SELECT ON SEQUENCE company_websites_id_seq TO nordabiz_app;

-- Migrate existing data: each company.website → company_websites row with is_primary=True
INSERT INTO company_websites (company_id, url, is_primary, source, created_at)
SELECT id, website, TRUE, 'migration', NOW()
FROM companies
WHERE website IS NOT NULL AND website != ''
ON CONFLICT DO NOTHING;
