-- Foodlinkk Command Center — Fase 2-4

CREATE TABLE IF NOT EXISTS monitored_sites (
    id SERIAL PRIMARY KEY,
    url TEXT NOT NULL,
    label VARCHAR(255),
    check_interval_min INTEGER DEFAULT 60,
    last_status VARCHAR(32),
    last_checked_at TIMESTAMPTZ,
    enabled BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS page_changes (
    id SERIAL PRIMARY KEY,
    site_id INTEGER REFERENCES monitored_sites(id) ON DELETE CASCADE,
    change_type VARCHAR(64) DEFAULT 'content',
    summary TEXT,
    diff_hash VARCHAR(64),
    detected_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS crawl_logs (
    id SERIAL PRIMARY KEY,
    site_id INTEGER REFERENCES monitored_sites(id) ON DELETE CASCADE,
    status_code INTEGER,
    duration_ms INTEGER,
    error_message TEXT,
    crawled_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS knowledge_documents (
    id SERIAL PRIMARY KEY,
    title VARCHAR(512) NOT NULL,
    source VARCHAR(128),
    doc_type VARCHAR(64) DEFAULT 'general',
    storage_path TEXT,
    chroma_id VARCHAR(128),
    metadata JSONB DEFAULT '{}',
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS halal_documents (
    id SERIAL PRIMARY KEY,
    title VARCHAR(512) NOT NULL,
    cert_body VARCHAR(255),
    expiry_date DATE,
    status VARCHAR(64) DEFAULT 'valid',
    storage_path TEXT,
    metadata JSONB DEFAULT '{}',
    created_at TIMESTAMPTZ DEFAULT NOW()
);

INSERT INTO monitored_sites (url, label, last_status, last_checked_at)
SELECT 'https://foodlinkk.com', 'Foodlinkk main', 'ok', NOW()
WHERE NOT EXISTS (SELECT 1 FROM monitored_sites WHERE url = 'https://foodlinkk.com');

INSERT INTO suppliers (name, country, category, moq, lead_time_days, rating)
SELECT 'Global Spice Co', 'IN', 'Spices', 500, 21, 4.2
WHERE NOT EXISTS (SELECT 1 FROM suppliers WHERE name = 'Global Spice Co');
