-- Migration 068: Link CompanyWebsiteAnalysis to CompanyWebsite
-- Purpose: Enable per-website audit cards in company profile

-- Add FK column
ALTER TABLE company_website_analysis
ADD COLUMN IF NOT EXISTS company_website_id INTEGER REFERENCES company_websites(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS idx_cwa_company_website_id ON company_website_analysis(company_website_id);

GRANT ALL ON TABLE company_website_analysis TO nordabiz_app;

-- Link existing analyses to matching company_websites by URL
-- Normalize: strip trailing slashes and protocol for matching
UPDATE company_website_analysis cwa
SET company_website_id = cw.id
FROM company_websites cw
WHERE cwa.company_id = cw.company_id
  AND cwa.company_website_id IS NULL
  AND LOWER(TRIM(TRAILING '/' FROM REPLACE(REPLACE(cwa.website_url, 'https://', ''), 'http://', '')))
    = LOWER(TRIM(TRAILING '/' FROM REPLACE(REPLACE(cw.url, 'https://', ''), 'http://', '')));
