-- Add seating and ticket type functionality

-- Create seating maps table
CREATE TABLE seating_maps (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  name TEXT NOT NULL,
  description TEXT,
  venue_name TEXT NOT NULL,
  layout_data JSONB NOT NULL, -- Store SVG/JSON layout data
  total_capacity INTEGER NOT NULL DEFAULT 0,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Create ticket types table
CREATE TABLE ticket_types (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  event_id UUID REFERENCES events(id) ON DELETE CASCADE NOT NULL,
  name TEXT NOT NULL, -- e.g., "General Admission", "VIP", "Balcony"
  description TEXT,
  price DECIMAL(10,2) NOT NULL,
  quantity_available INTEGER, -- NULL for unlimited
  quantity_sold INTEGER DEFAULT 0,
  seating_section TEXT, -- Reference to section in seating map
  seating_map_id UUID REFERENCES seating_maps(id),
  sale_start_time TIMESTAMP WITH TIME ZONE,
  sale_end_time TIMESTAMP WITH TIME ZONE,
  is_active BOOLEAN DEFAULT true,
  sort_order INTEGER DEFAULT 0,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  
  CONSTRAINT valid_quantities CHECK (quantity_sold <= COALESCE(quantity_available, quantity_sold))
);

-- Create seats table for assigned seating
CREATE TABLE seats (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  seating_map_id UUID REFERENCES seating_maps(id) ON DELETE CASCADE NOT NULL,
  seat_number TEXT NOT NULL, -- e.g., "A1", "B12"
  section TEXT NOT NULL, -- e.g., "Orchestra", "Balcony"
  row_name TEXT NOT NULL, -- e.g., "A", "B"
  seat_in_row INTEGER NOT NULL, -- 1, 2, 3, etc.
  x_position DECIMAL(8,3), -- X coordinate for visual positioning
  y_position DECIMAL(8,3), -- Y coordinate for visual positioning
  is_accessible BOOLEAN DEFAULT false,
  seat_type TEXT DEFAULT 'standard', -- standard, wheelchair, companion
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  
  UNIQUE(seating_map_id, seat_number)
);

-- Update tickets table to support ticket types and seats
ALTER TABLE tickets
ADD COLUMN ticket_type_id UUID REFERENCES ticket_types(id),
ADD COLUMN seat_id UUID REFERENCES seats(id),
ADD COLUMN seat_number TEXT, -- For general admission or when seat_id is not used
ADD COLUMN section TEXT; -- For general admission sections

-- Update events table to support seating maps
ALTER TABLE events
ADD COLUMN seating_map_id UUID REFERENCES seating_maps(id),
ADD COLUMN seating_type VARCHAR(20) DEFAULT 'general_admission'; -- 'general_admission', 'assigned_seating', 'mixed'

-- Create indexes for performance
CREATE INDEX idx_ticket_types_event_id ON ticket_types(event_id);
CREATE INDEX idx_ticket_types_active ON ticket_types(is_active);
CREATE INDEX idx_seats_seating_map_id ON seats(seating_map_id);
CREATE INDEX idx_seats_section ON seats(section);
CREATE INDEX idx_tickets_ticket_type_id ON tickets(ticket_type_id);
CREATE INDEX idx_tickets_seat_id ON tickets(seat_id);

-- Enable RLS on new tables
ALTER TABLE seating_maps ENABLE ROW LEVEL SECURITY;
ALTER TABLE ticket_types ENABLE ROW LEVEL SECURITY;
ALTER TABLE seats ENABLE ROW LEVEL SECURITY;

-- RLS Policies for seating_maps
CREATE POLICY "Anyone can view seating maps" ON seating_maps
  FOR SELECT USING (true);

CREATE POLICY "Users can create seating maps" ON seating_maps
  FOR INSERT WITH CHECK (true);

CREATE POLICY "Users can update their seating maps" ON seating_maps
  FOR UPDATE USING (true);

-- RLS Policies for ticket_types
CREATE POLICY "Anyone can view active ticket types" ON ticket_types
  FOR SELECT USING (is_active = true OR event_id IN (
    SELECT id FROM events WHERE organization_id IN (
      SELECT organization_id FROM users WHERE id = auth.uid()
    )
  ));

CREATE POLICY "Users can manage ticket types for their events" ON ticket_types
  FOR ALL USING (event_id IN (
    SELECT id FROM events WHERE organization_id IN (
      SELECT organization_id FROM users WHERE id = auth.uid()
    )
  ));

-- RLS Policies for seats
CREATE POLICY "Anyone can view seats" ON seats
  FOR SELECT USING (true);

CREATE POLICY "Users can manage seats" ON seats
  FOR ALL USING (true);

-- Insert some sample seating maps
INSERT INTO seating_maps (name, description, venue_name, layout_data, total_capacity) VALUES
(
  'Small Theater Layout',
  'Intimate theater with 100 seats in 10 rows',
  'Black Canyon Theater',
  '{
    "type": "theater",
    "sections": [
      {
        "name": "Orchestra",
        "rows": 10,
        "seatsPerRow": 10,
        "startRow": "A",
        "pricing": "standard"
      }
    ],
    "dimensions": {"width": 500, "height": 400}
  }',
  100
),
(
  'Concert Hall Layout',
  'Large concert hall with multiple sections',
  'Mountain View Concert Hall',
  '{
    "type": "concert_hall",
    "sections": [
      {
        "name": "Floor",
        "capacity": 500,
        "type": "general_admission"
      },
      {
        "name": "Balcony",
        "rows": 8,
        "seatsPerRow": 20,
        "startRow": "AA",
        "pricing": "premium"
      }
    ],
    "dimensions": {"width": 800, "height": 600}
  }',
  660
),
(
  'Wedding Reception Layout',
  'Round tables for wedding reception',
  'Aspen Lodge',
  '{
    "type": "reception",
    "sections": [
      {
        "name": "Main Floor",
        "tables": 12,
        "seatsPerTable": 8,
        "tableNumbers": [1,2,3,4,5,6,7,8,9,10,11,12]
      }
    ],
    "dimensions": {"width": 600, "height": 500}
  }',
  96
);

-- Create function to automatically update quantity_sold when tickets are created
CREATE OR REPLACE FUNCTION update_ticket_type_quantity()
RETURNS TRIGGER AS $$
BEGIN
  IF TG_OP = 'INSERT' THEN
    UPDATE ticket_types 
    SET quantity_sold = quantity_sold + 1
    WHERE id = NEW.ticket_type_id;
    RETURN NEW;
  ELSIF TG_OP = 'DELETE' THEN
    UPDATE ticket_types 
    SET quantity_sold = GREATEST(0, quantity_sold - 1)
    WHERE id = OLD.ticket_type_id;
    RETURN OLD;
  END IF;
  RETURN NULL;
END;
$$ LANGUAGE plpgsql;

-- Create triggers for automatic quantity updates
CREATE TRIGGER ticket_quantity_insert_trigger
  AFTER INSERT ON tickets
  FOR EACH ROW
  WHEN (NEW.ticket_type_id IS NOT NULL)
  EXECUTE FUNCTION update_ticket_type_quantity();

CREATE TRIGGER ticket_quantity_delete_trigger
  AFTER DELETE ON tickets
  FOR EACH ROW
  WHEN (OLD.ticket_type_id IS NOT NULL)
  EXECUTE FUNCTION update_ticket_type_quantity();

-- Add comments for clarity
COMMENT ON TABLE seating_maps IS 'Venue seating layouts that can be reused across events';
COMMENT ON TABLE ticket_types IS 'Different ticket categories for events (GA, VIP, etc.)';
COMMENT ON TABLE seats IS 'Individual seats for assigned seating venues';
COMMENT ON COLUMN ticket_types.seating_section IS 'References section name in seating_map layout_data';
COMMENT ON COLUMN events.seating_type IS 'general_admission, assigned_seating, or mixed';
COMMENT ON COLUMN tickets.seat_number IS 'Seat identifier for general admission or display purposes';
COMMENT ON COLUMN tickets.section IS 'Section name for organization purposes';