-- Migration: 005_add_removal_tracking
-- Description: Add 'removed' status support and removal tracking for community stations
-- Date: 2025-12-21

-- Step 1: Drop and recreate status check constraint to add 'removed' status
ALTER TABLE community_stations
  DROP CONSTRAINT IF EXISTS community_stations_status_check;

ALTER TABLE community_stations
  ADD CONSTRAINT community_stations_status_check
  CHECK (status IN ('pending', 'approved', 'rejected', 'removed'));

-- Step 2: Create removal_reports table for tracking "No longer has Premium 93" reports
CREATE TABLE IF NOT EXISTS station_removal_reports (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  station_id UUID NOT NULL REFERENCES community_stations(id) ON DELETE CASCADE,
  reported_by VARCHAR(255) NOT NULL,
  reason TEXT DEFAULT 'No longer has Premium 93',
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,

  -- Each user can only report a station once
  CONSTRAINT unique_user_station_report UNIQUE (station_id, reported_by)
);

-- Step 3: Create indexes for efficient queries
CREATE INDEX IF NOT EXISTS idx_removal_reports_station_id ON station_removal_reports(station_id);
CREATE INDEX IF NOT EXISTS idx_removal_reports_reported_by ON station_removal_reports(reported_by);

-- Step 4: Add columns for removal tracking to community_stations
ALTER TABLE community_stations
  ADD COLUMN IF NOT EXISTS removal_report_count INTEGER NOT NULL DEFAULT 0;

ALTER TABLE community_stations
  ADD COLUMN IF NOT EXISTS removed_at TIMESTAMP WITH TIME ZONE;

-- Step 5: Create trigger to update removal_report_count when reports are added
CREATE OR REPLACE FUNCTION update_removal_report_count()
RETURNS TRIGGER AS $$
BEGIN
  IF TG_OP = 'INSERT' THEN
    UPDATE community_stations
    SET removal_report_count = removal_report_count + 1,
        updated_at = CURRENT_TIMESTAMP
    WHERE id = NEW.station_id;
  ELSIF TG_OP = 'DELETE' THEN
    UPDATE community_stations
    SET removal_report_count = GREATEST(removal_report_count - 1, 0),
        updated_at = CURRENT_TIMESTAMP
    WHERE id = OLD.station_id;
  END IF;
  RETURN NULL;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trigger_update_removal_report_count ON station_removal_reports;

CREATE TRIGGER trigger_update_removal_report_count
AFTER INSERT OR DELETE ON station_removal_reports
FOR EACH ROW
EXECUTE FUNCTION update_removal_report_count();
