alter table "public"."organizations" drop column "hashed_api_key";

alter table "public"."organizations" add column "api_key" text not null default ''::text;

alter table "public"."organizations" add column "description" text not null default ''::text;

create table "public"."chat_messages" (
    "id" bigint generated by default as identity not null,
    "role" text not null,
    "content" text not null,
    "conversation_index" integer not null,
    "org_id" bigint not null,
    "conversation_id" bigint not null,
    "name" text,
    "created_at" timestamp with time zone not null default now()
);
alter table "public"."chat_messages" enable row level security;

-- Ensure the role is valid
alter table "public"."chat_messages" add constraint "chat_messages_role_method_check" CHECK ((role = ANY (ARRAY['user'::text, 'assistant'::text, 'function'::text]))) not valid;
alter table "public"."chat_messages" validate constraint "chat_messages_role_method_check";

create table "public"."conversations" (
    "id" bigint generated by default as identity not null,
    "created_at" timestamp with time zone not null default now(),
    "org_id" bigint not null
);
alter table "public"."conversations" enable row level security;

CREATE UNIQUE INDEX conversations_pkey ON public.conversations USING btree (id);

CREATE UNIQUE INDEX steps_pkey ON public.chat_messages USING btree (id);

alter table "public"."chat_messages" add constraint "steps_pkey" PRIMARY KEY using index "steps_pkey";

alter table "public"."conversations" add constraint "conversations_pkey" PRIMARY KEY using index "conversations_pkey";

alter table "public"."chat_messages" add constraint "chat_messages_conversation_id_fkey" FOREIGN KEY (conversation_id) REFERENCES conversations(id) ON DELETE CASCADE not valid;
alter table "public"."chat_messages" validate constraint "chat_messages_conversation_id_fkey";

alter table "public"."chat_messages" add constraint "chat_messages_org_id_fkey" FOREIGN KEY (org_id) REFERENCES organizations(id) ON DELETE CASCADE not valid;
alter table "public"."chat_messages" validate constraint "chat_messages_org_id_fkey";

alter table "public"."conversations" add constraint "conversations_org_id_fkey" FOREIGN KEY (org_id) REFERENCES organizations(id) ON DELETE CASCADE not valid;
alter table "public"."conversations" validate constraint "conversations_org_id_fkey";

create policy "Enable all on conversations for authenticated users based on org_id"
on "public"."conversations"
to authenticated
using ((auth.uid() IN ( SELECT profiles.id
   FROM profiles
  WHERE (profiles.org_id = conversations.org_id))));

create policy "Enable all on chat_messages for authenticated users based on org_id"
on "public"."chat_messages"
to authenticated
using ((auth.uid() IN ( SELECT profiles.id
   FROM profiles
  WHERE (profiles.org_id = chat_messages.org_id))));

alter table "public"."organizations" add column "api_host" text not null default ''::text;
