# Database Setup

> Create `.env.local` if it does not exist.
> The app pins `search_path` to the `DATABASE_URL` username, so a schema with that
> exact name must exist. `public` cannot be a username — it is a reserved role.

## User Input

Ask via **AskUserQuestion**: **"Do you already have a Postgres database created for this project?"** — options `Yes` / `No`.

## Branch A — Existing database

1. Ask: **"Please provide the database connection details"**.

   Fill the host in automatically — QAS is always `10.82.36.60:5432`, PRD is always `10.82.36.50:5432`.

2. Update `.env.local`:
   - Set `DATABASE_URL=postgres://<schema-username>:<password>@<server-address>:5432/<database-name>`.

## Branch B — No database

Ask via **AskUserQuestion**: **"Would you like me to create a local Postgres database using Docker?"** — options `Yes` / `No`.

- **No** → continue to next step.
- **Yes** → execute the Docker flow below.

### Docker flow

The container name is `<project-name>-postgres` where `<project-name>` is the kebab-case project name (read from the `name` field in `package.json`).

1. Ensure the Docker daemon is running. If not, start Docker Desktop via terminal automatically.
2. Auto-generate password.
3. Discover occupied ports by listing **all** containers (including stopped) and pick the first port in **5432 → 5450** that does **not** appear in the output. If all ports are occupied, stop and inform the user.
4. Run the container on the chosen port:

```powershell
docker run --name <project-name>-postgres -e POSTGRES_PASSWORD=<password> -d -p <PORT>:5432 postgres
```

- **Success** → continue.
- **Error** → stop and show the full error to the user.

5. Create the schema matching the username:

```powershell
docker exec <project-name>-postgres psql -U postgres -c "CREATE SCHEMA IF NOT EXISTS postgres AUTHORIZATION postgres;"
```

6. Update `.env.local`:
   - Set `DATABASE_URL=postgres://postgres:<password>@localhost:<PORT>/postgres`.
7. Output exactly:
   > ✅ Local Postgres database created successfully on port [PORT]
