-- +migrate Up
-- Migration: Enhance match entity with negotiation history and contract details
-- Description: Add negotiation_history table and enhance matches table with new fields

-- Create negotiation_history table
CREATE TABLE IF NOT EXISTS negotiation_history (
    id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
    match_id TEXT NOT NULL,
    timestamp TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
    actor_id TEXT,
    action VARCHAR(50) NOT NULL,
    notes TEXT,
    old_value JSONB,
    new_value JSONB,
    attachments JSONB DEFAULT '[]'::jsonb,
    metadata JSONB DEFAULT '{}'::jsonb,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT fk_negotiation_history_match
        FOREIGN KEY (match_id) REFERENCES matches(id) ON DELETE CASCADE
);

-- Add indexes for performance
CREATE INDEX IF NOT EXISTS idx_negotiation_history_match_id ON negotiation_history(match_id);
CREATE INDEX IF NOT EXISTS idx_negotiation_history_timestamp ON negotiation_history(timestamp);
CREATE INDEX IF NOT EXISTS idx_negotiation_history_actor ON negotiation_history(actor_id);

-- Add new columns to matches table
ALTER TABLE matches ADD COLUMN IF NOT EXISTS contract_contract_id TEXT;
ALTER TABLE matches ADD COLUMN IF NOT EXISTS contract_signed_at TIMESTAMP WITH TIME ZONE;
ALTER TABLE matches ADD COLUMN IF NOT EXISTS contract_effective_from TIMESTAMP WITH TIME ZONE;
ALTER TABLE matches ADD COLUMN IF NOT EXISTS contract_termination_date TIMESTAMP WITH TIME ZONE;
ALTER TABLE matches ADD COLUMN IF NOT EXISTS contract_value_per_year DECIMAL(12,2);
ALTER TABLE matches ADD COLUMN IF NOT EXISTS contract_terms_url TEXT;
ALTER TABLE matches ADD COLUMN IF NOT EXISTS contract_payment_terms TEXT;
ALTER TABLE matches ADD COLUMN IF NOT EXISTS contract_termination_terms TEXT;
ALTER TABLE matches ADD COLUMN IF NOT EXISTS contract_signatures JSONB DEFAULT '[]'::jsonb;

ALTER TABLE matches ADD COLUMN IF NOT EXISTS cancelled_by TEXT;
ALTER TABLE matches ADD COLUMN IF NOT EXISTS cancelled_at TIMESTAMP WITH TIME ZONE;

-- Add indexes for new columns
CREATE INDEX IF NOT EXISTS idx_matches_cancelled_by ON matches(cancelled_by);
CREATE INDEX IF NOT EXISTS idx_matches_contract_signed_at ON matches(contract_signed_at);
