
-- API settings (single row, admin-managed)
CREATE TABLE public.api_settings (
  id int PRIMARY KEY DEFAULT 1,
  base_url text NOT NULL DEFAULT 'http://118.179.129.98/myportal/api/rechargeapi/recharge_api_thirdparty.php',
  access_id text NOT NULL DEFAULT '',
  access_pass text NOT NULL DEFAULT '',
  enabled boolean NOT NULL DEFAULT false,
  updated_at timestamptz NOT NULL DEFAULT now(),
  CONSTRAINT api_settings_singleton CHECK (id = 1)
);

GRANT SELECT, INSERT, UPDATE, DELETE ON public.api_settings TO authenticated;
GRANT ALL ON public.api_settings TO service_role;

ALTER TABLE public.api_settings ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Admins manage api settings" ON public.api_settings
  FOR ALL TO authenticated
  USING (public.has_role(auth.uid(), 'admin'))
  WITH CHECK (public.has_role(auth.uid(), 'admin'));

INSERT INTO public.api_settings (id) VALUES (1) ON CONFLICT DO NOTHING;

-- Recharge logs
CREATE TABLE public.recharge_logs (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id uuid NOT NULL,
  refid text NOT NULL UNIQUE,
  operator text NOT NULL,
  number_type text NOT NULL DEFAULT '1',
  number text NOT NULL,
  amount numeric NOT NULL,
  status text NOT NULL DEFAULT 'PENDING',
  recharge_status text,
  provider_trxid text,
  message text,
  raw_response jsonb,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
);

GRANT SELECT ON public.recharge_logs TO authenticated;
GRANT ALL ON public.recharge_logs TO service_role;

ALTER TABLE public.recharge_logs ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Users view own recharge logs" ON public.recharge_logs
  FOR SELECT TO authenticated
  USING (auth.uid() = user_id OR public.has_role(auth.uid(), 'admin'));

CREATE INDEX recharge_logs_user_idx ON public.recharge_logs(user_id, created_at DESC);
