-- AI usage tracking for companies and job seekers
-- Supports per-day rate limiting for AI generation features

BEGIN;

-- Track AI usage per company per day
CREATE TABLE IF NOT EXISTS company_ai_usage (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    company_id UUID NOT NULL REFERENCES company_profiles(id) ON DELETE CASCADE,
    usage_date DATE NOT NULL DEFAULT CURRENT_DATE,
    generations_used INTEGER NOT NULL DEFAULT 0,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(company_id, usage_date)
);

-- Track AI usage per job seeker per day
CREATE TABLE IF NOT EXISTS job_seeker_ai_usage (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    job_seeker_id UUID NOT NULL REFERENCES job_seeker_profiles(id) ON DELETE CASCADE,
    usage_date DATE NOT NULL DEFAULT CURRENT_DATE,
    generations_used INTEGER NOT NULL DEFAULT 0,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(job_seeker_id, usage_date)
);

-- Indexes for fast lookups
CREATE INDEX IF NOT EXISTS idx_company_ai_usage_company_date ON company_ai_usage(company_id, usage_date);
CREATE INDEX IF NOT EXISTS idx_job_seeker_ai_usage_seeker_date ON job_seeker_ai_usage(job_seeker_id, usage_date);

-- job_applications was never created by any active migration until now
-- (only referenced, never defined — see crates/db/src/models/application.rs)
-- so this ALTER always failed and — since the whole file runs in one
-- transaction — rolled back company_ai_usage/job_seeker_ai_usage above too.
-- Self-create a minimal version; the later migration that fully owns this
-- table (20260721000000_fix_job_seeker_profile_and_applications.up.sql)
-- converges the rest of the columns via ADD COLUMN IF NOT EXISTS.
CREATE TABLE IF NOT EXISTS job_applications (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    job_id UUID NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
    applicant_user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    cover_note TEXT,
    status VARCHAR(50) NOT NULL DEFAULT 'APPLIED',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(job_id, applicant_user_id)
);

-- Add applied_via_ai flag to job_applications for AI auto-apply tracking
ALTER TABLE job_applications ADD COLUMN IF NOT EXISTS applied_via_ai BOOLEAN DEFAULT false;

-- Add ai_pack field to job_seeker_profiles for quick lookup (cached from pricing_packages)
ALTER TABLE job_seeker_profiles ADD COLUMN IF NOT EXISTS has_ai_pack BOOLEAN DEFAULT false;

COMMIT;