/*
  # Create Client Charge Mapped Table

  1. New Tables
    - `client_charge_mapped`
      - `id` (uuid, primary key) - Unique identifier
      - `orgacode` (text) - Organization code from projects table
      - `pet_eventcode` (text) - Event code from transaction_events_master
      - `ptr_trancode` (text) - Transaction code from transaction_codes
      - `created_at` (timestamptz) - Creation timestamp
      - `updated_at` (timestamptz) - Last update timestamp

  2. Constraints
    - Unique constraint on (orgacode, pet_eventcode, ptr_trancode)
    - This ensures no duplicate mappings for the same combination

  3. Security
    - Enable RLS on the table
    - Add policies for authenticated users to manage mappings
*/

CREATE TABLE IF NOT EXISTS client_charge_mapped (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  orgacode text NOT NULL,
  pet_eventcode text NOT NULL,
  ptr_trancode text NOT NULL,
  created_at timestamptz DEFAULT now(),
  updated_at timestamptz DEFAULT now(),
  CONSTRAINT unique_client_charge_mapping UNIQUE (orgacode, pet_eventcode, ptr_trancode)
);

-- Enable RLS
ALTER TABLE client_charge_mapped ENABLE ROW LEVEL SECURITY;

-- Create policies
CREATE POLICY "Authenticated users can view client charge mappings"
  ON client_charge_mapped FOR SELECT
  TO authenticated
  USING (true);

CREATE POLICY "Authenticated users can insert client charge mappings"
  ON client_charge_mapped FOR INSERT
  TO authenticated
  WITH CHECK (true);

CREATE POLICY "Authenticated users can update client charge mappings"
  ON client_charge_mapped FOR UPDATE
  TO authenticated
  USING (true)
  WITH CHECK (true);

CREATE POLICY "Authenticated users can delete client charge mappings"
  ON client_charge_mapped FOR DELETE
  TO authenticated
  USING (true);

-- Create indexes for foreign key lookups
CREATE INDEX IF NOT EXISTS idx_client_charge_mapped_orgacode ON client_charge_mapped(orgacode);
CREATE INDEX IF NOT EXISTS idx_client_charge_mapped_pet_eventcode ON client_charge_mapped(pet_eventcode);
CREATE INDEX IF NOT EXISTS idx_client_charge_mapped_ptr_trancode ON client_charge_mapped(ptr_trancode);