-- Migration 054: Competitor Monitoring
-- Tracks competitors and periodic snapshots for change detection
-- Date: 2026-02-06

CREATE TABLE IF NOT EXISTS company_competitors (
    id SERIAL PRIMARY KEY,
    company_id INTEGER REFERENCES companies(id) ON DELETE CASCADE,
    competitor_place_id VARCHAR(255) NOT NULL,
    competitor_name VARCHAR(255),
    competitor_address VARCHAR(500),
    competitor_rating NUMERIC(2,1),
    competitor_review_count INTEGER,
    competitor_category VARCHAR(255),
    competitor_website VARCHAR(500),
    added_by VARCHAR(20) DEFAULT 'auto', -- auto, manual
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW(),
    UNIQUE(company_id, competitor_place_id)
);

CREATE TABLE IF NOT EXISTS competitor_snapshots (
    id SERIAL PRIMARY KEY,
    competitor_id INTEGER REFERENCES company_competitors(id) ON DELETE CASCADE,
    snapshot_date DATE NOT NULL,
    rating NUMERIC(2,1),
    review_count INTEGER,
    photo_count INTEGER,
    posts_count INTEGER,
    has_website BOOLEAN,
    has_description BOOLEAN,
    data JSONB, -- full snapshot data
    changes JSONB, -- delta vs previous snapshot
    created_at TIMESTAMP DEFAULT NOW(),
    UNIQUE(competitor_id, snapshot_date)
);

CREATE INDEX IF NOT EXISTS idx_competitors_company ON company_competitors(company_id);
CREATE INDEX IF NOT EXISTS idx_competitors_active ON company_competitors(is_active);
CREATE INDEX IF NOT EXISTS idx_snapshots_competitor ON competitor_snapshots(competitor_id);
CREATE INDEX IF NOT EXISTS idx_snapshots_date ON competitor_snapshots(snapshot_date);

-- Permissions
GRANT ALL ON TABLE company_competitors TO nordabiz_app;
GRANT ALL ON TABLE competitor_snapshots TO nordabiz_app;
GRANT USAGE, SELECT ON SEQUENCE company_competitors_id_seq TO nordabiz_app;
GRANT USAGE, SELECT ON SEQUENCE competitor_snapshots_id_seq TO nordabiz_app;
